package com.zl.gmadmin.service.auth;

import cn.hutool.json.JSONUtil;
import com.zl.gmadmin.entity.SysMenu;
import com.zl.gmadmin.entity.SysRole;
import com.zl.gmadmin.entity.SysUser;
import com.zl.gmadmin.service.SysMenuService;
import com.zl.gmadmin.service.SysRoleService;
import com.zl.gmadmin.service.SysUserService;
import com.zl.gmadmin.utils.LogUtil;
import com.zl.gmadmin.vo.user.UserPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhangliang
 * @version 1.0
 * @date 2021/2/2 14:55
 */
@Service
public class CustomUserDetailsService   implements UserDetailsService {

    private final SysUserService sysUserService;


    private final SysRoleService sysRoleService;


    private final SysMenuService sysMenuService;

    public CustomUserDetailsService(SysUserService sysUserService, SysRoleService sysRoleService, SysMenuService sysMenuService) {
        this.sysUserService = sysUserService;
        this.sysRoleService = sysRoleService;
        this.sysMenuService = sysMenuService;
    }


    @Override
    public UserDetails loadUserByUsername(String usernameOrEmailOrPhone) throws UsernameNotFoundException {
        LogUtil.debug(usernameOrEmailOrPhone+":"+"获取用户验证信息");
        SysUser user=null;
        user = sysUserService.findByUsernameOrEmailOrPhone(usernameOrEmailOrPhone).get();
        LogUtil.debug(JSONUtil.toJsonStr(user));
        List<SysRole> roles=sysRoleService.selectByUserId(user.getUserId());
        Set<Long> rolesId=roles.stream().map(SysRole::getId).collect(Collectors.toSet());
        List<SysMenu> menus=sysMenuService.selectByRoleIdList(rolesId);
       UserDetails userDetails=UserPrincipal.create(user,roles,menus);


        return userDetails;
    }


}
